import { Injectable } from '@nestjs/common';
import { ICheckCaptchaByIDApiParams, ISendSMSApiParams } from './types';
// import { CreateSmDto } from './dto/create-sm.dto';
// import { UpdateSmDto } from './dto/update-sm.dto';
import * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $Util from '@alicloud/tea-util';
import { v4 as uuidv4 } from 'uuid';
import * as dayjs from 'dayjs';

import prismaClient from '@/config/prismaClient';
import { aliSmsInit } from '@/config/aliInstance';
import { generateCaptcha } from '@/utils/base/index';
import { throwHttpException } from '@/utils/nesjUtils';
import { ErrCode } from '@/types/globalType';
@Injectable()
export class SmsService {
  async sendSms(params: ISendSMSApiParams) {
    const code = generateCaptcha();
    const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      signName: process.env['ALIBABA_CLOUD_SIGN_NAME'],
      templateCode: params.SmsTypeCode,
      templateParam: JSON.stringify({
        code,
      }),
      phoneNumbers: params.Phone,
    });
    try {
      // 复制代码运行请自行打印 API 的返回值
      const res = await aliSmsInit().sendSmsWithOptions(
        sendSmsRequest,
        new $Util.RuntimeOptions({}),
      );
      const ID = uuidv4();
      await prismaClient.base_sms.create({
        data: {
          ID,
          SMSCode: code,
          Phone: params.Phone,
          AliSignName: process.env['ALIBABA_CLOUD_SIGN_NAME'],
          AliTemplateCode: params.SmsTypeCode,
          AliBizId: res.body.bizId,
          AliApiCode: res.body.code,
          AliApiMessage: res.body.message,
          AliApiResponse: res.toMap(),
          Creator: 'sys',
          CreateTime: dayjs().toISOString(),
          LastModifier: 'sys',
          LastModifyTime: dayjs().toISOString(),
        },
      });
      console.log('发送 接口');

      if (res.body.code == 'OK') {
        return {
          state: '1',
          msg: '',
          data: { ID },
        };
      } else {
        return {
          state: '0',
          msg: '发送短信失败！' + res.body.message,
          data: '',
        };
      }
    } catch (error) {
      // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
      // 错误 message
      // console.log('失败', error.message);
      // 诊断地址
      // console.log(error.data['Recommend']);
      throwHttpException({
        errCode: ErrCode.ALI_SMS_ERROR,
        errMsg: '发送短信失败！',
        errStack: error,
      });
    }
  }

  async checkCaptchaByID(params: ICheckCaptchaByIDApiParams) {
    const res = await prismaClient.base_sms.findMany({
      where: {
        ID: params.ID,
        AliTemplateCode: params.SmsTypeCode,
      },
    });
    if (res.length == 0) {
      return {
        state: '0',
        msg: '短信单据ID不正确，请检查！',
        data: '',
      };
    }
    if (res[0].SMSCode != params.CaptchaCode) {
      return {
        state: '0',
        msg: '验证码错误，请检查！',
        data: '',
      };
    }
    if (
      dayjs(dayjs().toISOString()).diff(dayjs(res[0].CreateTime), 'minute') > 5
    ) {
      return {
        state: '0',
        msg: '验证码已过期，请检查！',
        data: '',
      };
    }
    return {
      state: '1',
      msg: '验证成功！',
      data: '',
    };
  }
}
